<template>
  <div class="data-view">
    <div class="data-head">
      <div class="head-start">
        <slot name="head-start"></slot>
      </div>
      <div class="head-center">
        <slot name="head-center"></slot>
      </div>
      <div class="head-end">
        <el-button @click="handleChangeType" size="mini" icon="el-icon-sort">{{ typeTitle }}编辑</el-button>
      </div>
    </div>
    <div class="data-body">
      <slot name="body-center">
        <DataKeyValue v-show="typeValue === 'keyvalue'" :columns="columns" :value="value" />
        <DataRow v-show="typeValue === 'text'" :columns="columns" :value="value" />
      </slot>
    </div>
  </div>
</template>

<script>
import DataRow from './row.vue'
import DataKeyValue from './key-value.vue'
import keyValueColumns from '../constant/key-value-columns.js'

export default {
  components: {
    DataRow,
    DataKeyValue
  },

  props: {
    columns: {
      default () {
        return keyValueColumns
      }
    },
    value: {
      default () {
        return []
      }
    }
  },

  data () {
    return {
      typeList: [
        {text: '文本', value: 'text'},
        {text: '键值对', value: 'keyvalue'}
      ],
      typeValue: 'keyvalue',
      typeTitle: '文本'
    }
  },

  watch: {
    value: {
      deep: true,
      handler () {
        this.refresh()
      }
    }
  },

  methods: {
    // 切换编辑类型
    handleChangeType () {
      let list = this.typeList
      let index = list.findIndex(item => item.value === this.typeValue)
      let next = index + 1 > list.length - 1 ? 0 : index + 1
      this.typeValue = list[next].value
      next = next + 1 > list.length - 1 ? 0 : next + 1
      this.typeTitle = list[next].text
      this.$emit('type-change', { value: this.typeValue })
    },
    refresh () {

    }
  }
}
</script>

<style lang="less" scoped>
.data-view {
  .data-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 8px;
  }
  .head-start:not(:empty) + .head-center {
    padding-left: 8px;
  }
  .head-center {
    flex: 1;
    padding: 0 8px 0 0;
  }
  .head-end {
    display: flex;
    align-items: center;
  }
}
</style>